package com.yimixian.app.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

/**
 * 处理字符串工具类
 * 
 * @author
 * 
 */
public class StringUtils {

	/**
	 *是否是中文 
	 */
	public static boolean isChinese(char c) {

		return Character.toString(c).matches("[\\u4E00-\\u9FA5]+");
	}

	/**
	 * 字符串转换unicode
	 */
	public static String string2Unicode(String string) {
	 
	    StringBuffer unicode = new StringBuffer();
	 
	    for (int i = 0; i < string.length(); i++) {
	 
	        // 取出每一个字符
	        char c = string.charAt(i);
	 
	        // 转换为unicode
	        unicode.append("\\u" + Integer.toHexString(c));
	    }
	 
	    return unicode.toString();
	}
	
	/**
	 * unicode 转字符串
	 */
	public static String unicode2String(String unicode) {
	 
	    StringBuffer string = new StringBuffer();
	 
	    String[] hex = unicode.split("\\\\u");
	 
	    for (int i = 1; i < hex.length; i++) {
	 
	        // 转换出每一个代码点
	        int data = Integer.parseInt(hex[i], 16);
	 
	        // 追加成string
	        string.append((char) data);
	    }
	 
	    return string.toString();
	}
	
	/**
	 * 判断是否为空
	 * 
	 * @param text
	 * @return
	 */
	public static boolean isNullOrEmpty(String text) {
		if (text == null || "".equals(text.trim()) || text.trim().length() == 0 || "null".equals(text.trim())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获得MD5加密字符串
	 * 
	 * @param str
	 *            字符串
	 * @return
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}

	/**
	 * 对流转化成字符串
	 * 
	 * @param is
	 * @return
	 */
	public static String getStringByStream(InputStream is) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line + "\n");
			}
			return buffer.toString().replaceAll("\n\n", "\n");
		} catch (OutOfMemoryError o) {
			System.gc();
		} catch (Exception e) {
		}
		return null;
	}
	/**
	 * 得到字符串长度
	 * 
	 * @param text
	 * @return
	 */
	public static int getCharCount(String text) {
		String Reg = "^[\u4e00-\u9fa5]{1}$";
		int result = 0;
		for (int i = 0; i < text.length(); i++) {
			String b = Character.toString(text.charAt(i));
			if (b.matches(Reg))
				result += 2;
			else
				result++;
		}
		return result;
	}

	/**
	 * 获取截取后的字符串
	 * 
	 * @param text
	 *            原字符串
	 * @param length
	 *            截取长度
	 * @return
	 */
	public static String getSubString(String text, int length) {
		return getSubString(text, length, true);
	}

	/**
	 * 获取截取后的字符串
	 * 
	 * @param text
	 *            原字符串
	 * @param length
	 *            截取长度
	 * @param isOmit
	 *            是否加上省略号
	 * @return
	 */
	public static String getSubString(String text, int length, boolean isOmit) {
		if (isNullOrEmpty(text)) {
			return "";
		}
		if (getCharCount(text) <= length + 1) {
			return text;
		}

		StringBuffer sb = new StringBuffer();
		String Reg = "^[\u4e00-\u9fa5]{1}$";
		int result = 0;
		for (int i = 0; i < text.length(); i++) {
			String b = Character.toString(text.charAt(i));
			if (b.matches(Reg)) {
				result += 2;
			} else {
				result++;
			}

			if (result <= length + 1) {
				sb.append(b);
			} else {
				if (isOmit) {
					sb.append("...");
				}
				break;
			}
		}
		return sb.toString();
	}

	/**
	 * 电话号码验证
	 * 
	 * @param phoneNumber
	 *            手机号码
	 * @return
	 */
	public static boolean validatePhoneNumber(String phoneNumber) {
		Pattern pattern = Pattern.compile("^((13[0-9])|(15[0-9])|(18[0-9])|(14[0-9])|(17[0-9]))\\d{8}$");
		Matcher m = pattern.matcher(phoneNumber);
		return m.matches();
	}

	/**
	 * 邮箱验证
	 * 
	 * @param mail
	 *            邮箱
	 * @return
	 */
	public static boolean validateEmail(String mail) {
		Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = pattern.matcher(mail);
		return m.matches();
	}

	/**
	 * 验证字符串内容是否合法
	 * 
	 * @param content
	 *            字符串内容
	 * @return
	 */
	public static boolean validateLegalString(String content) {
		String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
		boolean legal = true;
		L1: for (int i = 0; i < content.length(); i++) {
			for (int j = 0; j < illegal.length(); j++) {
				if (content.charAt(i) == illegal.charAt(j)) {
					legal = false;
					break L1;
				}
			}
		}
		return legal;
	}

	/**
	 * 获取更新的时间
	 * 
	 * @param dateStr
	 * @return
	 * @throws Exception
	 */
	public static String getCreateString(String dateStr) {
		if (dateStr != null && !"".equals(dateStr)) {
			try {
				if (dateStr.indexOf(".") > -1) {
					dateStr = dateStr.substring(0, dateStr.indexOf("."));
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(dateStr);
				Calendar calendar = Calendar.getInstance();

				int oneMinuteUnit = 60;
				int oneHourUnit = 60 * 60;
				int oneDayUnit = 60 * 60 * 24;
				long i = (calendar.getTimeInMillis() - date.getTime()) / 1000;
				if (i < oneMinuteUnit && i > 0) {
					return i + "秒前";
				} else if (i < oneHourUnit && i > oneMinuteUnit) {
					return i / 60 + "分钟前";
				} else if (i < oneDayUnit && i > oneHourUnit) {
					return (i / (60 * 60)) + "小时前";
				} else {
					return dateStr;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 获取更新的时间
	 * 
	 * @param dateStr
	 * @return
	 * @throws Exception
	 */
	public static String getCreateString(Date date) {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (calendar.get(Calendar.YEAR) - (date.getYear() + 1900) > 0) {
			return sdf.format(date);
		} else if (calendar.get(Calendar.MONTH) - date.getMonth() > 0) {
			return sdf.format(date);
		} else if (calendar.get(Calendar.DAY_OF_MONTH) - date.getDate() > 0) {
			return sdf.format(date);
		} else if (calendar.get(Calendar.HOUR_OF_DAY) - date.getHours() > 0) {
			int i = calendar.get(Calendar.HOUR_OF_DAY) - date.getHours();
			return i + "小时前";
		} else if (calendar.get(Calendar.MINUTE) - date.getMinutes() > 0) {
			int i = calendar.get(Calendar.MINUTE) - date.getMinutes();
			return i + "分钟前";
		} else if (calendar.get(Calendar.SECOND) - date.getSeconds() > 0) {
			int i = calendar.get(Calendar.SECOND) - date.getSeconds();
			return i + "秒前";
		} else {
			return sdf.format(date);
		}
	}
	
	/**
	 * 计算时间间隔
	 * @param date
	 * @return
	 */
	public static String getDateSpace(Date date) {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date curDate = new Date();
		int curTimeSeond = (int) curDate.getTime();
		int beforeTimeSeond = (int) date.getTime();
		int spaceTime = (curTimeSeond - beforeTimeSeond) / 1000;
		if(spaceTime < 60){
			return spaceTime + "秒前";
		}else if(spaceTime < 60 * 60){
			return spaceTime / 60 + "分钟前";
		}else if(spaceTime < 60 * 60 * 24){
			return spaceTime / 60 / 60 + "小时前";
		}else{
			return sdf.format(date);
		}
		
	}

	/**
	 * 对搜房的图片进行动态调整
	 * 
	 * @param coverimg
	 * @param width
	 * @param height
	 * @return
	 */
	public static String getImgPath(String coverimg, int width, int height) {
		if (isNullOrEmpty(coverimg)) {
			return "";
		}
		if (!coverimg.startsWith("http")) {
			return coverimg;
		}
		try {
			URL url = new URL(coverimg);
			if (url.getHost().indexOf("soufun") == -1) {
				return coverimg;
			}
		} catch (MalformedURLException e) {
			return "";
		}

		String http = coverimg.substring(7);
		String head = http.substring(0, http.indexOf("/"));
		String xurl = coverimg.replace("http://" + head, "");
		xurl = xurl.substring(0, xurl.lastIndexOf("."));
		String xend = coverimg.substring(coverimg.lastIndexOf("."));
		String h = String.valueOf(height);
//		if(width==480&&height==440){
//			
//		}else{
//			h = h + "c4";
//		}
		if (coverimg.indexOf("viewimage") > -1) {
			coverimg = coverimg.substring(0, coverimg.lastIndexOf("/")) + "/" + width + "x" + h + xend;
		} else {
			coverimg = "http://" + head + "/viewimage" + xurl + "/" + width + "x" + h + xend;
		}
		return coverimg;
	}

	/**
	 * 如果为空显示暂无信息
	 * 
	 * @param tv
	 *            控件名
	 * @param str
	 *            信息
	 */
	public static void viewText(TextView tv, String str) {
		if (isNullOrEmpty(str)) {
			tv.setText("暂无资料");
		} else {
			tv.setText(str);
		}
	}

	/**
	 * 对流转化成字符串
	 * 
	 * @param is
	 * @return
	 */
	public static String getContentByString(InputStream is) {
		try {
			if (is == null)
				return null;
			byte[] b = new byte[1024];
			int len = -1;
			StringBuilder sb = new StringBuilder();
			while ((len = is.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			return sb.toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 截取字符串，去掉sign后边的
	 * 
	 * @param source
	 *            原始字符串
	 * @param sign
	 * @return
	 */
	public static String splitByIndex(String source, String sign) {
		String temp = "";
		if (isNullOrEmpty(source)) {
			return temp;
		}
		int length = source.indexOf(sign);
		if (length > -1) {
			temp = source.substring(0, length);
		} else {
			return source;
		}
		return temp;
	}

	/**
	 * 保留小数点后一位
	 * 
	 * @param d
	 * @return
	 * @throws Exception
	 */
	public static String formatNumber(double d) {
		try {
			DecimalFormat df = new DecimalFormat("#,##0.0");
			return df.format(d);
		} catch (Exception e) {
		}
		return "";
	}

	public static String formatNumber(String d) {
		return formatNumber(Double.parseDouble(d));
	}




	/*
	 * 获取字符串格式的当前时间
	 */
	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/*
	 * 时间格式转换，yyyy-MM-dd xx:xx:xx为：yyyy-MM-dd
	 */
	public static String getStringDate(String date) {

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date d = new Date();
		try {
			d = formatter.parse(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String dateString = formatter.format(d);
		return dateString;

	}

	/*
	 * 截取sign后边的数字
	 */
	public static String getStringNum(String str, String sign) {
		String reg = ":split:";
		return str.replace(sign, reg).replaceAll(reg + "\\d+", "").replaceAll(" ", "").trim();

	}

	/*
	 * 时间格式转换，yyyy-MM-dd xx:xx:xx为：MM-dd xx:xx 不要年和秒
	 */
	public static String getStringForDate(String date) {

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat f = new SimpleDateFormat("MM-dd HH:mm");
		Date d = new Date();
		try {
			d = formatter.parse(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String dateString = f.format(d);
		return dateString;

	}

	/*
	 * 判断价格是否为0或空
	 */
	public static boolean isPriceZero(String price) {
		if (isNullOrEmpty(price)) {
			return true;
		}
		price = splitByIndex(price, ".");
		if ("0".equals(price)) {
			return true;
		}
		return false;

	}

	/**
	 * 取价格的整数，去掉单位
	 * 
	 * @param price
	 * @return
	 */
	public static String getPrice(String price) {
		Pattern p = Pattern.compile("^\\d+");
		Matcher m = p.matcher(price);
		if (m.find()) {
			return m.group();
		}
		return "";
	}

	/**
	 * 判断是否全为数字
	 * 
	 * @param content
	 * @return
	 */
	public static boolean isAllNumber(String content) {
		boolean isAllNumber = true;
		if (isNullOrEmpty(content)) {
			return false;
		}
		for (int i = 0; i < content.length(); i++) {
			if (content.charAt(i) < '0' || content.charAt(i) > '9') {
				isAllNumber = false;
			}
		}
		return isAllNumber;
	}

	/**
	 * 整数转字节数组
	 * 
	 * @param i
	 * @return
	 */
	public static byte[] intToByte(int i) {
		byte[] bt = new byte[4];
		bt[0] = (byte) (0xff & i);
		bt[1] = (byte) ((0xff00 & i) >> 8);
		bt[2] = (byte) ((0xff0000 & i) >> 16);
		bt[3] = (byte) ((0xff000000 & i) >> 24);
		return bt;
	}

	/**
	 * 字节数组转整数
	 * 
	 * @param bytes
	 * @return
	 */
	public static int bytesToInt(byte[] bytes) {
		int num = bytes[0] & 0xFF;
		num |= ((bytes[1] << 8) & 0xFF00);
		num |= ((bytes[2] << 16) & 0xFF0000);
		num |= ((bytes[3] << 24) & 0xFF000000);
		return num;
	}

	public static CharSequence formateTime(int time) {
		int mHour,mMinute,mSecond;//时分秒
		StringBuilder sb_time = new StringBuilder();
		mHour = time/3600;
		if(mHour>9)
			sb_time.append(mHour+":");
		else if(mHour >= 0){
			sb_time.append("0"+mHour+":");
		}else{
			sb_time.append("00:");
		}
		time = time%3600;
		mMinute = time/60;
		if(mMinute>9){
			sb_time.append(mMinute+":");
		}else if(mMinute>=0){
			sb_time.append("0"+mMinute+":");
		}else{
			sb_time.append("00:");
		}
		mSecond = time%60;
		if(mSecond>9){
			sb_time.append(mSecond);
		}else if(mSecond>=0){
			sb_time.append("0"+mSecond);
		}
		return sb_time.toString();
	}

	/**  
     * @return 返回指定笔和指定字符串的长度  
     */  
    public static float getFontLength(Paint paint, String str) {  
        return paint.measureText(str);  
    }  
    /**  
     * @return 返回指定笔的文字高度  
     */  
    public static float getFontHeight(Paint paint)  {    
        FontMetrics fm = paint.getFontMetrics();   
        return fm.descent - fm.ascent;    
    }   
    /**  
     * @return 返回指定笔离文字顶部的基准距离  
     */  
    public static float getFontLeading(Paint paint)  {    
        FontMetrics fm = paint.getFontMetrics();   
        return fm.leading - fm.ascent;    
    }  
	
    /**
     * text着色(指定文本着色)
     * @param origionStr 原始全字符串
     * @param coloredStr 要着色的字符串数组
     * @param color 着色颜色数组(与字符串数组对应)
     * @return
     */
    public static SpannableStringBuilder getColorText(String origionStr, String[] coloredStrs, int[] colors){
    	SpannableStringBuilder style = new SpannableStringBuilder(origionStr);
    	try {
    		for (int i = 0; i < colors.length; i++) {
    			if(isNullOrEmpty(coloredStrs[i]))
    				continue;
    			String[] splits = null;
				try {
					splits = origionStr.split(coloredStrs[i], -1);
				} catch (Exception e) {
//					e.printStackTrace();
					//如果输入了正则判断的特殊符号需要转义
//					splits = origionStr.split("\\" + coloredStrs[i], -1);
					continue;
				}
    			int curLength = 0;
				for (int j = 0; j < splits.length - 1; j++) {
    				style.setSpan(new ForegroundColorSpan(colors[i]), curLength + splits[j].length(), 
    						curLength + splits[j].length() + coloredStrs[i].length(), 
    						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    				curLength += splits[j].length() + coloredStrs[i].length();
    			}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return style;
    }
    
    /**
     * text着色(指定文本着色)
     * @param origionStr 原始全字符串
     * @param coloredStr 要着色的字符串数组
     * @param color 着色颜色
     * @return
     */
    public static SpannableStringBuilder getColorText(String origionStr, String[] coloredStrs, int color){
    	SpannableStringBuilder style = new SpannableStringBuilder(origionStr);
    	
    		try {
				for (int i = 0; i < coloredStrs.length; i++) {
					if(isNullOrEmpty(coloredStrs[i]))
						continue;
					String[] splits = null;
					try {
						splits = origionStr.split(coloredStrs[i], -1);
					} catch (Exception e) {
//						e.printStackTrace();
						//如果输入了正则判断的特殊符号需要转义
//						splits = origionStr.split("\\" + coloredStrs[i], -1);
						continue;
					}
					int curLength = 0;
					for (int j = 0; j < splits.length - 1; j++) {
						style.setSpan(new ForegroundColorSpan(color), curLength + splits[j].length(), 
								curLength + splits[j].length() + coloredStrs[i].length(), 
								Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
						curLength += splits[j].length() + coloredStrs[i].length();
					}
					
				}
			} catch (Exception e) {
//				e.printStackTrace();
			}
    	
    	return style;
    }
    
    /**
     * text着色(指定文本统一着色)
     * @param origionStr 原始全字符串
     * @param coloredStr 要着色的字符串
     * @param color 着色颜色
     * @return
     */
    public static SpannableStringBuilder getColorText(String origionStr, String coloredStr, int color){
    	SpannableStringBuilder style = new SpannableStringBuilder(origionStr);
    	try {
    		String[] splits = null;
    		try {
    			splits = origionStr.split(coloredStr, -1);
			} catch (Exception e) {
//	    		e.printStackTrace();
				//如果输入了正则判断的特殊符号需要转义
//	    		splits = origionStr.split("\\" + coloredStr, -1);
				return style;
	    	}
			int curLength = 0;
			for (String split : splits) {
				style.setSpan(new ForegroundColorSpan(color), curLength + split.length(), 
						curLength + split.length() + coloredStr.length(), 
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				curLength += split.length() + coloredStr.length();
			}
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return style;
    }
    
}
